﻿using Autofac;
using MediatR;
using System.Reflection;

namespace CSharp.Basic.Learn.MediatR
{
  public class MediatRModule :Autofac.Module
  {
    protected override void Load(ContainerBuilder builder)
    {
      builder.RegisterAssemblyTypes(typeof(IMediator).GetTypeInfo().Assembly)
             .AsImplementedInterfaces();

      // Register all the Command classes (they implement IRequestHandler) in assembly holding the Commands
      // 在包含命令的程序集中注册所有Command类（它们实现IRequestHandler）
      //builder.RegisterAssemblyTypes(typeof(CreateOrderCommand).GetTypeInfo().Assembly)
      //    .AsClosedTypesOf(typeof(IRequestHandler<,>));

      // Register the DomainEventHandler classes (they implement INotificationHandler<>) in assembly holding the Domain Events
      // 在包含域事件的程序集中注册DomainEventHandler类（它们实现INotificationHandler <>）
      builder.RegisterAssemblyTypes(typeof(TestNotificationHanlder).GetTypeInfo().Assembly)
          .AsClosedTypesOf(typeof(INotificationHandler<>));

      // Register the Command's Validators (Validators based on FluentValidation library)
      // 注册Command的验证器（基于FluentValidation库的验证器）
      //builder
      //    .RegisterAssemblyTypes(typeof(CreateOrderCommandValidator).GetTypeInfo().Assembly)
      //    .Where(t => t.IsClosedTypeOf(typeof(IValidator<>)))
      //    .AsImplementedInterfaces();


      builder.Register<ServiceFactory>(context =>
      {
        var componentContext = context.Resolve<IComponentContext>();
        return t => { return componentContext.TryResolve(t, out object o) ? o : null; };
      });

      //builder.RegisterGeneric(typeof(LoggingBehavior<,>)).As(typeof(IPipelineBehavior<,>));
      //builder.RegisterGeneric(typeof(ValidatorBehavior<,>)).As(typeof(IPipelineBehavior<,>));

    }
  }
}
